package org.sjs.dreamfly.data

import com.squareup.moshi.Types
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.sjs.dreamfly.model.HistoryItem
import org.sjs.dreamfly.common.util.JsonUtil
import org.sjs.dreamfly.common.util.PhemonUtils

@Deprecated("废弃此类封装")
private class HistoryDataProvider: DataCenter.DataProvider {

    companion object {
        const val HISTORY_FILE_DIR = "/history/"
    }

    private var historyList = mutableListOf<HistoryItem>()

//    fun saveHistoryItem(videoInfo: VideoInfo, progress: Long) {
//        var item = historyList.find {
//            videoInfo.videoUrl == it.videoInfo.videoUrl
//        }
//        if (item == null) {
//            item = HistoryItem(videoInfo, progress, System.currentTimeMillis())
//            historyList.add(item)
//        } else {
//            item.progress = progress
//            item.modifyTime = System.currentTimeMillis()
//        }
//        storeToFile()
//    }

    fun getHistoryList(): MutableList<HistoryItem> {
        return historyList
    }

    fun storeToFile() {
        val context = PhemonUtils.getApplication()
        val content = JsonUtil.moshi.adapter<List<HistoryItem>>(Types.newParameterizedType(List::class.java, HistoryItem::class.java)).toJson(historyList)
        MainScope().launch {
            PhemonUtils.saveFile(context, context.cacheDir.absolutePath + HISTORY_FILE_DIR, content)
        }
    }

    fun loadFromFile() {
        val context = PhemonUtils.getApplication()
        MainScope().launch {
            PhemonUtils.loadFile(context, context.cacheDir.absolutePath + HISTORY_FILE_DIR)?.let {
                if (it.isNotEmpty()) {
                    historyList = JsonUtil.fromJson<MutableList<HistoryItem>>(it)?: mutableListOf()
                }
            }
        }
    }
}